package com.css.dzj.dzjjcss.modules.statistics.service.impl;

import com.css.dzj.dzjjcss.common.util.Constant;
import com.css.dzj.dzjjcss.common.util.ServiceUtil;
import com.css.dzj.dzjjcss.common.util.SnowflakeId;
import com.css.dzj.dzjjcss.common.util.excel.ExcelData;
import com.css.dzj.dzjjcss.common.util.excel.ExportExcelUtils;
import com.css.dzj.dzjjcss.modules.press.entity.Press;
import com.css.dzj.dzjjcss.modules.press.service.PressService;
import com.css.dzj.dzjjcss.modules.resultregister.entity.QResultRegisterEntity;
import com.css.dzj.dzjjcss.modules.resultregister.entity.ResultRegisterEntity;
import com.css.dzj.dzjjcss.modules.resultregister.mapper.ResultRegisterMapper;
import com.css.dzj.dzjjcss.modules.statistics.service.StatisticsService;
import com.css.dzj.dzjjcss.modules.todo.entity.JcssTodoEntity;
import com.css.dzj.dzjjcss.modules.todo.service.TodoService;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class StatisticsServiceImpl implements StatisticsService {
    @Autowired
    private ResultRegisterMapper registerMapper;
    @Autowired
    private JPAQueryFactory jpaQueryFactory;
    @Autowired
    private PressService pressService;
    @Autowired
    private TodoService todoService;
    @Autowired
    private HttpServletRequest request;

    @Override
    public QueryResults<ResultRegisterEntity> getPage(String projectName, String createUser, String createUserUnit, String status, String startTime, String endTime, String administrativeDivision, String supervisionType,String unitName ,PageRequest pageRequest) {
        QResultRegisterEntity q = QResultRegisterEntity.resultRegisterEntity;

        Predicate predicate = q.isNotNull().or(q.isNull());

        /* 根据用户组织名称：orgName，查询 */
        String orgName = ServiceUtil.getOrgName(request).replace("地震局","");
        String orgLevel = ServiceUtil.getOrgLevel(request);
        if (orgName == null || orgName.contains("中国")){
            // 中国地震局用户，查看状态为1的信息
            predicate =  ExpressionUtils.and(predicate, q.status.eq("1"));
        }
        if (orgName == null || !orgName.contains("中国地")){
            // 1.省级用户
            if ("1".equals(orgLevel)){
                // 待用：可以在表中新增一个parentOrgName,根据这个查询隶属关系
                predicate =  ExpressionUtils.and(predicate, q.orgName.contains(orgName));
            }
            // 地市级用户
            if ("2".equals(orgLevel)){
                predicate =  ExpressionUtils.and(predicate, q.orgName.eq(orgName));
            }
        }
        predicate = ("".equals(projectName) || projectName == null) ? predicate : ExpressionUtils.and(predicate, q.projectName.like("%" + projectName + "%"));
        predicate = ("".equals(createUser) || createUser == null) ? predicate : ExpressionUtils.and(predicate, q.createUser.like("%" + createUser + "%"));
        predicate = ("".equals(createUserUnit) || createUserUnit == null) ? predicate : ExpressionUtils.and(predicate, q.createUserUnit.like("%" + createUserUnit + "%"));
        predicate = ("".equals(createUserUnit) || createUserUnit == null) ? predicate : ExpressionUtils.and(predicate, q.createUserUnit.like("%" + createUserUnit + "%"));
        predicate = ("".equals(status) || status == null) ? predicate : ExpressionUtils.and(predicate, q.status.eq(status));
        predicate = ("".equals(administrativeDivision) || administrativeDivision == null) ? predicate : ExpressionUtils.and(predicate, q.administrativeDivision.like("%" + administrativeDivision + "%"));
        predicate = ("".equals(supervisionType) || supervisionType == null) ? predicate : ExpressionUtils.and(predicate, q.supervisionType.like("%" + supervisionType + "%"));
        predicate = ("".equals(unitName) || unitName == null) ? predicate : ExpressionUtils.and(predicate, q.unitName.like("%" + unitName + "%"));

            /** 只有结束时间 **/
            if ((StringUtils.isEmpty(startTime)) && (!StringUtils.isEmpty(endTime))) {
                Date endDate = null;
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
                try {
                    endDate = sf.parse(endTime+ " " + "23:59:59.999");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                predicate = ExpressionUtils.and(predicate, q.createTime.loe(endDate));
            }
            /** 只有开始时间 **/
            if ((!StringUtils.isEmpty(startTime)) && (StringUtils.isEmpty(endTime))) {
                Date startDate = null;
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    startDate = sf.parse(startTime);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                predicate = ExpressionUtils.and(predicate, q.createTime.goe(startDate));
            }
            /** 时间都不为空 **/
            if ((!StringUtils.isEmpty(startTime)) && (!StringUtils.isEmpty(endTime))) {
                Date startDate = null;
                Date endDate = null;
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
                try {
                    startDate = sf.parse(startTime);
                    endDate = sfd.parse(endTime+ " " + "23:59:59.999");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                predicate = ExpressionUtils.and(predicate, q.createTime.between(startDate, endDate));
            }

        predicate = ExpressionUtils.and(predicate, q.delFlag.eq(Constant.NO_DELETE));

        return jpaQueryFactory
                .selectFrom(q)
                .where(predicate)
                .orderBy(q.createTime.desc())
                .offset(pageRequest.getOffset())   //起始页
                .limit(pageRequest.getPageSize())  //每页大小
                .fetchResults();
    }

    @SneakyThrows
    @Override
    public void exportToExcel(HttpServletResponse response, List<ResultRegisterEntity> registerEntityList) {
        if (registerEntityList == null || registerEntityList.size() <= 0) {
            throw new RuntimeException("数据为空！");
        }
        //导出实体
        ExcelData data = new ExcelData();
        data.setName("地震监测设施监管信息表");
        /**
         * 设置Excel标题
         */
        ArrayList<String> titles = new ArrayList<>();
        titles.add("标题");
        titles.add("创建者");
        titles.add("创建者单位");
        titles.add("状态");
        titles.add("创建时间");
        titles.add("监管对象名称");
        titles.add("监管类别");
        titles.add("提交时间");
        titles.add("其它信息");
        titles.add("其他提示");
        data.setTitles(titles);
        /**
         * 处理行数据
         */
        ArrayList<List<Object>> rows = new ArrayList<>();
        for (ResultRegisterEntity registerEntity : registerEntityList) {
            ArrayList<Object> row = new ArrayList<>();
            row.add(registerEntity.getTitle());
            row.add(registerEntity.getCreateUser());
            row.add(registerEntity.getCreateUserUnit());
            if(registerEntity.getStatus().equals("0")){
                row.add("未提交");
            }else if(registerEntity.getStatus().equals("1")){
                row.add("已提交");
            }else if(registerEntity.getStatus().equals("2")){
                row.add("已撤回");
            }else{
                row.add("");
            }
            //row.add(registerEntity.getStatus());
            row.add(registerEntity.getCreateTime());
            row.add(registerEntity.getSupervisionObjectName());
            if(registerEntity.getSupervisionType().equals("0")){
                row.add("检测环境");
            }else if(registerEntity.getSupervisionType().equals("1")){
                row.add("其他");
            }else{
                row.add("");
            }
            //row.add(registerEntity.getSupervisionType());
            row.add(registerEntity.getSubmitTime());
            row.add(registerEntity.getOtherMsg());
            row.add(registerEntity.getOtherTip());
            rows.add(row);
        }
        data.setRows(rows);
        // 导出
        ExportExcelUtils.exportExcel(response, "地震监测设施监管信息表.xlsx", data);

    }

    @Override
    public List<Object[]> chartList() {
        return registerMapper.chartList();
    }

    @Transactional
    @Override
    public void urge(Press press) {
        // 催办新增一条数据
        press.setId(SnowflakeId.getId());
        pressService.add(press);
        // 并且新增一条代办数据
        this.setTodo(press);
    }

    @Override
    public ResultRegisterEntity queryById(String id) {
        return registerMapper.findById(id).get();
    }

    /**
     * 催办-进入代办表
     *
     * @param press
     */
    private void setTodo(Press press) {
        JcssTodoEntity todoEntity = new JcssTodoEntity();
        if (StringUtils.isEmpty(todoEntity.getId())) {
            todoEntity.setId(SnowflakeId.getId());
        }
        todoEntity.setTitle(press.getTitle());
        // 新增方法任务默认1：待办
        todoEntity.setStatus("1");
        todoEntity.setUrl("../todolist/cuiban.html");
        todoEntity.setLinkId(press.getId());
        todoEntity.setCreatePerson(ServiceUtil.getLoginName(request));
        todoEntity.setCreateTime(new Date());
        todoEntity.setDelFlag(Constant.NO_DELETE);
        todoService.add(todoEntity);
    }
}
